/* 
 * File:   ThresholdCalculator.cpp
 * Author: root
 * 
 * Created on October 28, 2015, 6:29 AM
 */

#include "ThresholdCalculator.h"

#include "Buffer.h"

using namespace std;

ThresholdCalculator* ThresholdCalculator::instance = 0;

ThresholdCalculator::ThresholdCalculator() {
    this->d = 21;
    this->e = 225;
}

ThresholdCalculator* ThresholdCalculator::getInstance()
{
  if ( !ThresholdCalculator::instance )
  {
        ThresholdCalculator::instance = new ThresholdCalculator();
  }
  return ThresholdCalculator::instance;
}

double ThresholdCalculator::getThreshold()
{
    return this->d;
}

double ThresholdCalculator::getDeviation()
{
    return this->e;
}


void ThresholdCalculator::release()
{
    if ( this->getInstance() )
    {
        delete this->getInstance();
    }
}


uint32 ThresholdCalculator::update(const SensorData *paraSensor)
{

    uint32 tempCnt = 0;
    double tempData = 0;
    double tempData1 = 0;
    double avgData = 0;
    uint32 result;

    if (this->sensorBuffer.cnt > 0) {
        if((paraSensor->time <= this->sensorBuffer.back()->time) 
                || (paraSensor->time > (this->sensorBuffer.back()->time + 1000)))
        {
            this->d = 21;
            this->e = 225;
            this->sensorBuffer.bottom = 0;
            this->sensorBuffer.top = 0;
            this->sensorBuffer.cnt = 0;
        }
    }

    if (this->sensorBuffer.cnt > 199) 
    {
        this->sensorBuffer.bottom = (this->sensorBuffer.bottom + 1) % 200;
        this->sensorBuffer.cnt--;
    }

    this->sensorBuffer.data[this->sensorBuffer.top] = * paraSensor;

    this->sensorBuffer.cnt++;
    this->sensorBuffer.top = (this->sensorBuffer.top + 1) % 200;

    result = 0;

    if ( this->sensorBuffer.cnt > 199 )
    {
        tempCnt = 0;
        avgData = 0;
        while ( tempCnt < this->sensorBuffer.cnt )
        {
            avgData += this->sensorBuffer.data[tempCnt++].accelerator;
        }

        avgData = avgData / 200;

        tempCnt = 0;

        do {
            tempData = this->sensorBuffer.data[tempCnt++].accelerator - avgData;
            tempData *= tempData;
            tempData1 += tempData;
        } while (tempCnt < this->sensorBuffer.cnt);

        this->e = tempData1 / 199;

        if (this->e >=2500) {
            this->d = 50; // 50
        } else if (this->e >= 400){
            this->d = 28; //28
        } else {
            this->d = 21; //21
        }
        if ( this->sensorBuffer.cnt > 50 )
        {
            this->sensorBuffer.bottom = (this->sensorBuffer.bottom + 50) % 200;
            tempData = this->sensorBuffer.cnt - 50;
        } else {
            tempData = 0;
            this->sensorBuffer.bottom = 0;
            this->sensorBuffer.top = 0;
        }
        result = 1;
        this->sensorBuffer.cnt = tempData;
    }
    return result;
}

